package net.sdd.school.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.sdd.school.entity.Subject;
import net.sdd.school.entity.vo.SubjectTreeVo;
import net.sdd.school.entity.vo.SubjectVo;
import net.sdd.school.mapper.SubjectMapper;
import net.sdd.school.service.ISubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Jet
 * @since 2022-08-19
 */
@Service
@Slf4j
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements ISubjectService {

    @Override
    public void importExcel(MultipartFile file) {
        try {
            EasyExcel.read(
                    file.getInputStream(),
                    SubjectVo.class, new PageReadListener<SubjectVo>(list -> {
                        for (SubjectVo vo : list) {
                            log.info("SubjectVo:{}", vo);
                            // 保存vo中课程分类信息到数据库
                            saveSubjects(vo);
                        }
                    })).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*@Override
    public List<SubjectTreeVo> findAllSubject() {
        //1. 定义返回结果
        List<SubjectTreeVo> result = new ArrayList<>();

        //2. 查询一级分类
        List<Subject> subjectOne = getSubjectByParentId("0");
        //3. 遍历一级分类
        for (Subject subject : subjectOne) {
            //4. 封装vo
            SubjectTreeVo vo = new SubjectTreeVo();
            vo.setId(subject.getId());
            vo.setTitle(subject.getTitle());
            // 封装二级类别
            List<Subject> subjectTwo = getSubjectByParentId(subject.getId());
            // 把List<Subject>转换为 List<SubjectTreeVo>
            List<SubjectTreeVo> children = new ArrayList<>();
            for (Subject s : subjectTwo) {
                SubjectTreeVo v = new SubjectTreeVo();
                v.setId(s.getId());
                v.setTitle(s.getTitle());
                children.add(v);
            }
            // 设置到vo
            vo.setChildren(children);

            //5. vo 添加到集合
            result.add(vo);
        }
        return result;
    }*/

    @Override
    public List<SubjectTreeVo> findAllSubject() {
        //1. 定义返回结果
        List<SubjectTreeVo> result = new ArrayList<>();

        //2. 查询一级分类
        List<Subject> subjectOne = getSubjectByParentId("0");
        //3. 遍历一级分类.
        subjectOne.forEach(subject -> {  // 这里的subject可以随便写，用来保存遍历的每一个元素
            //4. 封装vo
            SubjectTreeVo vo = new SubjectTreeVo();
            vo.setId(subject.getId());
            vo.setTitle(subject.getTitle());
            // 封装二级类别
            List<Subject> subjectTwo = getSubjectByParentId(subject.getId());
            // 把List<Subject>转换为 List<SubjectTreeVo>
            List<SubjectTreeVo> children = subjectTwo.stream().map(s->{//s表示集合的每一个元素
                SubjectTreeVo subjectTreeVo = new SubjectTreeVo();
                subjectTreeVo.setId(s.getId());
                subjectTreeVo.setTitle(s.getTitle());
                return subjectTreeVo;
            }).collect(Collectors.toList());

            vo.setChildren(children);

            //5. vo 添加到集合
            result.add(vo);
        });

        return result;
    }

    /**
     * 根据二级类别id查询
     *
     * @param parentId 值为0表示一级类别；否则是二级类别
     * @return
     */
    private List<Subject> getSubjectByParentId(String parentId) {
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);
        return this.list(wrapper);
    }

    /**
     * easyexcel 读取行，保存数据到db
     */
    private void saveSubjects(SubjectVo vo) {
        //1、保存一级分类
        //1.1、先根据一级分类查询
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", vo.getSubjectOne());
        wrapper.eq("parent_id", "0");
        Subject subjectOne = baseMapper.selectOne(wrapper);
        if (subjectOne == null) {
            subjectOne = new Subject();
            subjectOne.setTitle(vo.getSubjectOne());
            subjectOne.setParentId("0");
            baseMapper.insert(subjectOne);
        }
        //2、保存二级分类
        //2.1、获取一级分类id (mp保存后会自动填充对象主键值)
        String id = subjectOne.getId();
        //2.2、构造条件
        wrapper = new QueryWrapper<>();
        wrapper.eq("title", vo.getSubjectTwo());
        wrapper.eq("parent_id", id);
        //2.3、查询
        Subject subjectTwo = baseMapper.selectOne(wrapper);
        //2.4、如果没有查找则插入二级分类
        if (subjectTwo == null) {
            subjectTwo = new Subject();
            subjectTwo.setTitle(vo.getSubjectTwo());
            subjectTwo.setParentId(id);
            baseMapper.insert(subjectTwo);
        }
    }
}
